<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { UserFilled, QuestionFilled } from '@element-plus/icons-vue'
import { policiesGetListService } from '@/api/policies'
import { identityCreateService } from '@/api/identity'

const router = useRouter()

/* 表单管理 */
const form = ref()

const userModel = ref({
  username: '',
  password: '',
  policyList: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'submit' }
  ],
  password: [
  { required: true, message: '请输入密码', trigger: 'submit' }
  ]
}

/* 展示策略列表 */
const policiesList = ref([])

const getPoliciesList = async () => {
  const res = await policiesGetListService()
  policiesList.value = res.data.data
}
getPoliciesList()

/* 创建用户 */
const table = ref()

const createUser = async () => {
  // 校验表单数据
  await form.value.validate()
  // 获取已选数据
  const rows = table.value.getSelectionRows()
  const list = []
  rows.forEach(row => {
    list.push(row.id)
  });
  userModel.value.policyList = list.join(',')
  // 发送请求
  await identityCreateService(userModel.value)
  router.push('/identity')
}

</script>

<template>
  <mt-create-form>
    <el-form ref="form" :model="userModel" :rules="rules" label-width="auto">
      <el-form-item>
        <el-icon size="30">
          <UserFilled />
        </el-icon>
        <span style="font-weight: bold; margin-left: 8px">创建用户</span>
      </el-form-item>
      <el-form-item prop="username" label="用户名" label-position="left">
        <el-input v-model="userModel.username" name="name"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码" label-position="left">
        <el-input v-model="userModel.password" name="password"></el-input>
      </el-form-item>
      <el-form-item label="分配策略" label-position="top">
        <el-table ref="table" @row-click="onRowClick" :data="policiesList" highlight-current-row="true" row-style="cursor: pointer" v-loading="loading">
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="name" label="策略名"></el-table-column>

          <template #empty>
            <el-empty description="没有策略"></el-empty>
          </template>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button
          @click="createUser"
          type="default"
          color="black"
          size="large"
          style="margin-top: 20px; padding: 20px; position: absolute; right: 0"
          auto-insert-space
        >
          创建用户
        </el-button>
      </el-form-item>
    </el-form>

    <template #tip>
      <p style="display: flex; align-items: center">
        <el-icon size="30"><QuestionFilled /></el-icon
        ><span style="margin-left: 5px; font-weight: bold">了解有关用户功能的更多信息</span>
      </p>
      MT 用户由唯一的用户名和相应的密码组成。客户端必须通过指定现有 MT
      用户的用户名和相应的密码来验证其身份。
    </template>
  </mt-create-form>
</template>

<style lang="scss" scoped></style>
